#include "mainwindow.h"
#include "global_variable.h"
#include "Run/mainmenu.h"
#include <QGridLayout>
#include "Gas_Set/gasset_menu.h"
#include "softkeyboard_2.h"
QPushButton *focusBtn[8];
sysset *Sysset;
systemctl *Sysctrl;
sysstatus *Sysstatus;

typedef struct _pid
{
    float SetTemp;
    float pwmduty;
    float Kp,Ki,Kd;
    float pwm;
    float integral;
    float err;
    float err_last;
}pid;
pid pid1;
pid pid2;


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    this->setObjectName("MainWindow");

    the_background="QMainWindow{background-image: url(:/pic/背景图片.jpg);}";
    this->setStyleSheet(the_background);
    this->setFixedSize(640,480);

    Sysset = Init_Shm_Sysset();
    Sysctrl = Init_Shm_Ctl();
    Sysstatus = Init_Shm();
    Sysctrl->SYS_CTL_MODE = 0;
    Sysctrl->BD_Interface.Fflag = 1;//阀门控制切换标志 0:出来的时候为0  1:进去的时候为1
    Photometer_Integral.clear();
     Sysset->Avg_Time =Sysset->Avg_Time ; //光度计平均时间下标
     Photometer_Flag=Sysset->Phot_Cfg=0;//为了测试赋值为1;
    ui_Init();
    init_data();
   data_recordInit();
    data_Record();
    timer = new QTimer(this);
    timer->start(1000);
    timer2 = new QTimer(this);
    timer2->start(200);
   timer_wel = new QTimer(this);
    timer_wel->start(1);
    timer_CreateFile = new QTimer(this);
    timer_CreateFile->start(1000); //用于创建新文件/文件夹
    timer_flow = new QTimer(this);
    timer_flow2 = new QTimer(this);
    timer_flow3 = new QTimer(this);
    timer_flow4 = new QTimer(this);
    timer_m_time = new QTimer(this);
    timer_m_time->start(500); //通讯协议更新
    timer_tb = new QTimer(this);
    timer_tb->start(200);  //2s更新一次全部数据，也更新一次最新的记录间隔
    timer_file = new QTimer(this);
    timer_file->start(60000);//用于写入数据，10s往文件里写入一次数据zone_flag   改成默认的60分钟 60*60*1000

//    temp = cycle_flag;
//    timer_file->start(cycletime[cycle_flag].toFloat() * 60 *1000);//用于写入数据，10s往文件里写入一次数据zone_flag   改成默认的60分钟 60*60*1000
    timer_flow->start(1000);//1s更新一次显示数据
    timer_flow2->start(1000);//1s更新一次显示数据
    timer_flow3->setInterval(1000);//1s更新一次显示数据
    timer_flow3->start();//1s更新一次显示数据
    timer_flow4->start(1000);//1s更新一次显示数据
    timer_warncnt = new QTimer(this);
    timer_warncnt->start(1000); //更新警告数目
    timer_photo = new QTimer(this);
    timer_photo->start(100);
    time_Init();


}

MainWindow::~MainWindow()
{

}

void MainWindow::Warn_cnt()
{
    cnt_warn =0;
    if(Photometer_Flag)
    {
        if(!Sysstatus->BD_Phot_IsPresent)
            cnt_warn ++;
    }
    if(O3_Show_Flag)
    {
        if(!Sysstatus->BD_Ozo_IsPresent)
            cnt_warn++;
    }
    if(!Sysstatus->MFC_Zero_IsPresent ) cnt_warn ++;
    if(!Sysstatus->MFC_Air_IsPresent ) cnt_warn ++;
    if(!Sysstatus->BD_Int_IsPresent) cnt_warn ++;

    //臭氧温度
    if(O3_Show_Flag)
    if(Sysstatus->Ozo_TempRead < Sysset->Ozotemp_L || Sysstatus->Ozo_TempRead > Sysset->OzoTemp_H)
        cnt_warn++;
    //环境温度
    if(Sysstatus->Int_Temp1 < Sysset->BenchTemp_L || Sysstatus->Int_Temp1 >Sysset->BenchTemp_H)
        cnt_warn++;
    //光度计温度
    if(Photometer_Flag)
    if(Sysstatus->Phot_TempRead < Sysset->PhotTemp_L || Sysstatus->Phot_TempRead >Sysset->PhotTemp_H)
        cnt_warn++;
    //光池温度
    if(Photometer_Flag)
    if(Sysstatus->Int_Temp3 < Sysset->Light_Cell_L || Sysstatus->Int_Temp3 >Sysset->Light_Cell_H)
    {
        cnt_warn++;
    }

    //光强
    if(Photometer_Flag)
    if(Sysctrl->PhotoMeter_Mode)
    {
        if(Sysstatus->Light_Data[0] < Sysset->Light_Data_L || Sysstatus->Light_Data[0] >Sysset->Light_Data_H)
            cnt_warn++;
    }



}

void MainWindow::time_Init()
{

    //警告数目和标志更新
    connect(timer_warncnt,&QTimer::timeout,[=](){
        Warn_cnt();
        if(cnt_warn) theLabel[2]->show();
        else theLabel[2]->hide();
        if(flag_protect) theLabel[3]->show();
        else theLabel[3]->hide();
        if(Sysset->Lock_Status) theLabel[5]->show();
        else theLabel[5]->hide();

    });

    //定时器
    connect(timer2,&QTimer::timeout,[=](){
//        data_Record();
        data_collect();
    });
//    //数据记录，写入数据
    connect(timer_file,&QTimer::timeout,[=](){

        QString DirName2 = DirName+"/";
        dataFile::WriteFile(DirName2+FileName+".txt",finalData);//记录一次数据
    });
    //定时器
    connect(timer,&QTimer::timeout,[=](){
        QString timeNowHM = QDateTime::currentDateTime().toString("hh:mm:ss");
        QString timeNowYD = QDateTime::currentDateTime().toString("yyyy.MM.dd");
        QString TimeNow ="  "+timeNowHM+"\n"+timeNowYD;
        theLabel[1]->setText(TimeNow);
    });
    connect(timer_wel,&QTimer::timeout,[=](){
        if(Main_show_flag)
        {

            init_message *inshow = new init_message(this);
            inshow->show();
            Main_show_flag = 0;

        }
        else
        {
            timer_wel->stop();
        }
    });

    //1s进来一次
    connect(timer_CreateFile,&QTimer::timeout,[=](){
        QString daydirname = QDateTime::currentDateTime().toString("dd");
        QString mondirname = QDateTime::currentDateTime().toString("MM");
        //Day
        if(Day_filename!=daydirname)
        {
            Day_filename = daydirname;
            name = QDateTime::currentDateTime().toString("yyyy_MM_dd");
            QString DirName2 = DirName+"/";
            dataFile::WriteFile(DirName2+FileName+".txt",finalData);//记录一次数据
        }

        //Month
        if(Month_dirname != mondirname)
        {
            Month_dirname = mondirname;
            //Day  Update
            Day_filename = "";
            DirName ="/File_reMake/Datalog/"+ QDateTime::currentDateTime().toString("yyyy_MM");
            dataFile::CreateDir(DirName);
        }
    });

    //更新显示数据1
     connect(timer_flow,&QTimer::timeout,[=](){
         if((Sysctrl->Sys_Ozo_Sel) &&(Sysctrl->PhotoMeter_Mode!=3))//当不为光度计控制时
         {
             if(Sysctrl->Sys_Ozo_Sel>=1 && Sysctrl->Sys_Ozo_Sel <= 6)
                 O3_RN[0]=tr("臭氧发生器") +" "+QString::number(Sysctrl->Sys_Ozo_Sel);
             else if(Sysctrl->Sys_Ozo_Sel ==7)
                 O3_RN[0] = tr("手动");
              O3_RN[1]=QString("%1").arg(Sysset->Ozo_Span[Sysctrl->Sys_Ozo_Sel-1]);
              O3_RN[2]="%";
         }
        else if((Sysctrl->Sys_Ozo_Sel) &&(Sysctrl->PhotoMeter_Mode==3))//当为光度计控制时
         {
             O3_RN[0] = O3_RN[1] = O3_RN[2] = "";
//         ui->label_GasName_2->setText(O3_RN[0]);
//         ui->label_GasFlow_2->setText(O3_RN[1]);
//         ui->label_PPM_2->setText(O3_RN[2]);
         }
         else
             O3_RN[0] = O3_RN[1] = O3_RN[2] = "";
//         ui->label_GasName_2->setText(O3_RN[0]);
//         ui->label_GasFlow_2->setText(O3_RN[1]);
//         ui->label_PPM_2->setText(O3_RN[2]);
         //自动进行项目开始
         if(photo_flag)
         {
             test_daoji--;
         }
     });
        //更新显示数据2
         connect(timer_flow2,&QTimer::timeout,[=](){
         //实时显示气体浓度
         if(Sysctrl->Sys_Gas_Sel)
         {
             float all_flow  = Sysstatus->MFC_Zero_PostCal *1000 + Sysstatus->MFC_Air_PostCal;
             double  den_data = Sysstatus->MFC_Air_PostCal/(all_flow) * Sysset->Gas[Sysctrl->Sys_Gas_Sel-1].gasconcentration;
             if(all_flow < 1) den_data=0;     //Test
             float test_temp = den_data*1000 - (int)(den_data*1000); //1000 isnot  range
             if(test_temp==0) //less 3
                  data_nd=QString::number(den_data);
             else
                  data_nd =QString::number(den_data,'f',4);
             if(data_nd.toFloat()>=0.002 && Sysstatus->MFC_Air_PostCal && Sysstatus->MFC_Zero_PostCal &&!Sysset->Sys_Only_Ozo)
             {
                 gas_RN[1] = data_nd;
                 gas_RN[0] = Sysset->Gas[Sysctrl->Sys_Gas_Sel-1].gasname;
                 gas_RN[2] = "PPM";
             }
             else
             {
                 //这种是单独运行臭氧情况
                 if(Sysctrl->Sys_Span_Sel==8 && Sysctrl->Sys_Gas_Sel==1 && Sysset->Sys_Only_Ozo)
                     gas_RN[0] = gas_RN[2] =gas_RN[1] = "";
                 else
                 {
                     gas_RN[1] = "0";
                     gas_RN[0] = Sysset->Gas[Sysctrl->Sys_Gas_Sel-1].gasname;
                     gas_RN[2] = "PPM";
                 }
             }
         }
         else
             gas_RN[0] = gas_RN[2] =gas_RN[1] = "";
//         ui->label_GasName->setText(gas_RN[0]);
//         ui->label_GasFlow->setText(gas_RN[1]);
//         ui->label_PPM->setText(gas_RN[2]);
             if(Sysctrl->Ozo_Ppm>-50&&Sysctrl->Ozo_Ppm<50)
         Ozo_Ppm_2 = Sysctrl->Ozo_Ppm * Sysset->Ozo_K - Sysset->Ozo_B;       //当前值

         //为了探究电压调节臭氧浓度进行的积分
         Integral.append(Ozo_Ppm_2);
         if(Integral.length() > 3)
         {
             Integral.removeFirst();
         }
         float Integral_totalnumber=0;

         foreach (float num,Integral)//把各项list的值相加
         {
             Integral_totalnumber+=num;
         }
         Integral_aver_con = Integral_totalnumber/Integral.length();//进行平均值

         //光度计数据的积分
         Photometer_Integral.append(Ozo_Ppm_2);
         while(Photometer_Integral.length() > PhotoMeter_Mode_aver[Sysset->Avg_Time])
         {
             Photometer_Integral.removeFirst();
         }
         float totalnumber=0;

         foreach (float num, Photometer_Integral)//把各项list的值相加
         {
             totalnumber+=num;
         }
         aver_con = totalnumber/Photometer_Integral.length();//进行平均值


         Sysctrl->Show_Ozo = aver_con;       //当前值


          //快速校准页面
                 if(Sysctrl->Ozo_Cal_Flag == 1)       //校准系数
                 {
                    Sysset->Ozo_K  = Sysctrl->Sam_Ozo / aver_con * Sysset->Ozo_K;      //新系数 = 标准浓度/显示浓度*旧K值
                     // SysSetShadow->Ozo_K = SystemCtl->Sam_Ozo / SysStatus.Ozo_Ppm;
                    if(Sysset->Ozo_K>=0.5&&Sysset->Ozo_K<=2)
                    {
                        temp_K= Sysset->Ozo_K;
                        Sysctrl->Para_Save = 1;
                        Sysctrl->Ozo_Cal_Flag = 0;
                        temp_K_Flag=0;
                    }
                    else{
                       Sysset->Ozo_K =  temp_K;
                       Sysctrl->Para_Save = 1;
                       Sysctrl->Ozo_Cal_Flag = 0;
                       temp_K_Flag=1;
                    }
 //                    ui->btn_1->setText("Ozo_K"+QString::number(Sysset->Ozo_K,'f',3));
 //                    ui->btn_2->setText("Sam_Ozo"+QString::number(Sysctrl->Show_Ozo,'f',3));

                 }
                 if(Sysctrl->Ozo_Cal_Flag == 2)    //校准背景值
                 {
                     Sysset->Ozo_B = aver_con + Sysset->Ozo_B;        //新背景值 = 当前浓度+之前设置的背景值
                     Sysctrl->Para_Save = 1;
                     Sysctrl->Ozo_Cal_Flag = 0;
 //                    ui->btn_3->setText("Ozo_B"+QString::number(Sysset->Ozo_B,'f',3));
                 }
 //               Ozo_Ppm =  Sysctrl->Show_Ozo =aver_con;       //当前值
                 //因为Sysctrl->Show_Ozo容易被改写成0，导致数据错乱，所以在计算完以后马上保存到Ozo_Ppm
                 //当为外部的时候的pid调节
                  if(Sysctrl->PhotoMeter_Mode==3)
                  {

                      if(test_daoji<=0)
                      if((Sysctrl->Ozo_Ppm>0)&&(Sysctrl->BD_Ozonator.Vot_Set))
                      {
                          PPPPP=PID1_realize(Sysset->Set_Ozo_Con[Sysset->Sys_Ozo_Sel-1]);
                          Sysctrl->BD_Ozonator.Vot_Set = BD_Ozonator_Vot_Set+PPPPP;
                     if(Sysctrl->BD_Ozonator.Vot_Set>20.0)
                         Sysctrl->BD_Ozonator.Vot_Set = 20.0;
                     if(Sysctrl->BD_Ozonator.Vot_Set<0)
                         Sysctrl->BD_Ozonator.Vot_Set = 0;
                      }

                  }
                  if(!Sysctrl->PhotoMeter_Mode)
                    test_daoji=60;
     });

         //更新显示数据3
          connect(timer_flow3,&QTimer::timeout,[=](){
              if(Sysctrl->PhotoMeter_Mode)
              {
                  if(Sysctrl->PhotoMeter_Mode==1||Sysctrl->PhotoMeter_Mode==2)
                  {

                      Photometer_RN[0]=tr("O3");
                      Photometer_RN[1]=QString::number(Sysctrl->Show_Ozo,'f',3);
                      Photometer_RN[2]="PPM";
                  }
                 else if(Sysctrl->PhotoMeter_Mode==3)
                  {

                      Photometer_RN[0]=tr("O3");
                      Photometer_RN[1]=QString::number(Sysctrl->Show_Ozo,'f',3);
                      Photometer_RN[2]="PPM";
                      O3_RN[0] = O3_RN[1] = O3_RN[2] = "";
//                  ui->label_GasName_2->setText(O3_RN[0]);
//                  ui->label_GasFlow_2->setText(O3_RN[1]);
//                  ui->label_PPM_2->setText(O3_RN[2]);
                  }

              }
              else
                  Photometer_RN[0] = Photometer_RN[1] = Photometer_RN[2] = "";

//              label_Photometer->setText(Photometer_RN[0]);
//              label_Photometer2->setText(Photometer_RN[1]);
//              label_Photometer3->setText(Photometer_RN[2]);


      });



          //更新显示数据4
           connect(timer_flow4,&QTimer::timeout,[=](){
       if(photo_flag && flag_daojin)
       {
           if(daoji<=0)
           {
            flag_daojin = 0;
            photo_flag=0;
            timer_flow3->start();
            daoji=300;
           }
           else
           {
               Photometer_RN[0]=tr("O3");
               Photometer_RN[1]=(QString::number(daoji)+"秒");
               Photometer_RN[2]="PPM";
               daoji--;
//               label_Photometer->setText(Photometer_RN[0]);
//               label_Photometer2->setText(Photometer_RN[1]);
//               label_Photometer3->setText(Photometer_RN[2]);
               timer_flow3->stop();
           }

       }
       if((photo_flag==0) && (flag_daojin))
       {

           {
               Photometer_RN[0] = Photometer_RN[1] = Photometer_RN[2] = "";
//               label_Photometer->setText(Photometer_RN[0]);
//               label_Photometer2->setText(Photometer_RN[1]);
//               label_Photometer3->setText(Photometer_RN[2]);
               timer_flow3->start();
            daoji=300;
       }
       }
           //1s更新一次显示数据
       });

           //项目中进行已设定好的数值
            connect(timer_m_time,&QTimer::timeout,[=](){
           if(Sysset->Sys_Run[0])
           {
               //显示正在运行气体名字

               //传递运行数据
               if(Sysset->Sys_Gas_Sel>=1)
               {
                   Sysctrl->Sys_Gas_Sel = Sysset->Sys_Gas_Sel;
                   Sysctrl->Air_Consentration  = Sysset->Gas[Sysset->Sys_Gas_Sel-1].gasconcentration;//钢平气浓度
                    //标气
                    if(Sysset->Sys_Span_sel>0 && Sysset->Sys_Span_sel <7)
                       {
                           Sysctrl->Sys_Span_Sel = Sysset->Sys_Span_sel;
                           Sysctrl->Total_Flow = Sysset->Gas[Sysset->Sys_Gas_Sel-1].totalflow_span[Sysctrl->Sys_Span_Sel-1];
                           Sysctrl->Target_Consentration = Sysset->Gas[Sysset->Sys_Gas_Sel-1].gasconcentration_span[Sysctrl->Sys_Span_Sel-1];
                       }
                    //手动
                    else if(Sysset->Sys_Span_sel == 7)
                       {
                           Sysctrl->Sys_Span_Sel = Sysset->Sys_Span_sel;
                           Sysctrl->AirFlow = Sysset->Gas[Sysset->Sys_Gas_Sel-1].gasconcentration_span[6];
                           Sysctrl->Zero_Flow = Sysset->Gas[Sysset->Sys_Gas_Sel-1].totalflow_span[6];
                       }
                       //零气
                      else if(Sysset->Sys_Span_sel == 8)
                     {
                           Sysctrl->Sys_Span_Sel = Sysset->Sys_Span_sel;
                           Sysctrl->Sys_Span_Sel = Sysset->Sys_Span_sel = 8;
                           Sysctrl->Zero_Flow = Sysset->Gas[Sysset->Sys_Gas_Sel-1].zeroairflow;
                           Sysctrl->Total_Flow = Sysctrl->Zero_Flow;
                           Sysctrl->Target_Consentration = 0;
                     }
               }
               else if(Sysset->Sys_Ozo_Sel == 0)  //当前既不出标气也不出臭氧
               {
                   Sysctrl->Sys_Gas_Sel = Sysset->Sys_Gas_Sel= 0;
                   Sysctrl->Sys_Span_Sel =Sysset->Sys_Span_sel= 0;
                   Sysctrl->Total_Flow = 0;
                   Sysctrl->Target_Consentration = 0;
                   Sysset->Sys_Mode = 0;

               }

               //实时显示气体浓度
               if(Sysctrl->Sys_Gas_Sel)
               {

                   QString data_nd;
                   float all_flow  = Sysstatus->MFC_Zero_PostCal *1000 + Sysstatus->MFC_Air_PostCal;
                   double  den_data = Sysstatus->MFC_Air_PostCal/(all_flow) * Sysset->Gas[Sysctrl->Sys_Gas_Sel-1].gasconcentration;
                   if(all_flow < 1) den_data=0;     //Test
                   float test_temp = den_data*1000 - (int)(den_data*1000); //1000 isnot  range
                   if(test_temp==0) //less 3
                        data_nd=QString::number(den_data);
                   else
                        data_nd =QString::number(den_data,'f',4);
                   if(data_nd.toFloat()>=0.002 && Sysstatus->MFC_Air_PostCal && Sysstatus->MFC_Zero_PostCal &&!Sysset->Sys_Only_Ozo)
                   {
                       gas_RN[1] = data_nd;
                       gas_RN[0] = Sysset->Gas[Sysctrl->Sys_Gas_Sel-1].gasname;
                       gas_RN[2] = "PPM";
                   }
                   else
                   {
                       //这种是单独运行臭氧情况
                       if(Sysctrl->Sys_Span_Sel==8 && Sysctrl->Sys_Gas_Sel==1 && Sysset->Sys_Only_Ozo)
                           gas_RN[0] = gas_RN[2] =gas_RN[1] = "";
                       else
                       {
                           gas_RN[1] = "0";
                           gas_RN[0] = Sysset->Gas[Sysctrl->Sys_Gas_Sel-1].gasname;
                           gas_RN[2] = "PPM";
                       }
                   }
               }
               else
                   gas_RN[0] = gas_RN[2] =gas_RN[1] = "";
//               ui->label_GasName->setText(gas_RN[0]);
//               ui->label_GasFlow->setText(gas_RN[1]);
//               ui->label_PPM->setText(gas_RN[2]);
               //臭氧
               if(Sysset->Sys_Ozo_Sel==0)
               {
                   Sysctrl->Sys_Ozo_Sel=Sysset->Sys_Only_Ozo = 0;
                   Sysset->IS_OZO_ENABLE = 0;
                   Sysctrl->BD_Ozonator.Vot_Set = 0;
                   O3_RN[0]=O3_RN[1]=O3_RN[2]="";
//                   ui->label_GasName_2->setText(O3_RN[0]);
//                   ui->label_GasFlow_2->setText(O3_RN[1]);
//                   ui->label_PPM_2->setText(O3_RN[2]);
                   if(Sysset->Sys_Gas_Sel == 0)
                   {
                       Sysctrl->Sys_Gas_Sel = Sysset->Sys_Gas_Sel= 0;
                       Sysctrl->Sys_Span_Sel = Sysset->Sys_Span_sel= 0;
                       Sysctrl->Total_Flow = 0;
                       Sysctrl->Target_Consentration = 0;
                   }

                   if(Sysset->Sys_Run[1]==2) //外部
                    {
                       photo_flag=1;
                        Sysctrl->PhotoMeter_Mode=Sysset->Sys_Run[1];
                        Sysset->PHOT_ENABLE = 1;
                        Sysctrl->BD_Interface.Fflag = 0;//阀门控制切换标志 0:出来的时候为0  1:进去的时候为1
                        Sysctrl->BD_Photometer.Vot_Set = Sysset->Phot_Span *0.132+5.7 ;
                    }
                   else if(Sysset->Sys_Run[1]!=2)
                   {
                       Sysset->Sys_Run[1]=0;
                       Sysctrl->PhotoMeter_Mode=Sysset->Sys_Run[1];
                       Sysctrl->BD_Interface.Fflag = 1;//阀门控制切换标志 0:出来的时候为0  1:进去的时候为1
                       Sysctrl->BD_Photometer.Vot_Set =0;
                       Sysctrl->BD_Ozonator.Vot_Set = Sysset->Ozo_Span[Sysset->Sys_Ozo_Sel-1]*0.132+5.7;
                       Sysset->PHOT_ENABLE = 0;
                       Photometer_RN[0]=Photometer_RN[1]=Photometer_RN[2]="";
//                       label_Photometer->setText(Photometer_RN[0]);
//                       label_Photometer2->setText(Photometer_RN[1]);
//                       label_Photometer3->setText(Photometer_RN[2]);
                       photo_flag=0;
                   }
               }


               else if(Sysset->Sys_Run[1]!=3) //当光度计还未为控制时
               {
                   Sysctrl->PhotoMeter_Mode=Sysset->Sys_Run[1];
                   Sysset->IS_OZO_ENABLE = 1;
                   if(Sysset->Sys_Run[1]==0)
                   {
                       Sysset->PHOT_ENABLE = 0;
                       Sysctrl->BD_Photometer.Vot_Set =0;
                       Sysctrl->BD_Ozonator.Vot_Set = Sysset->Ozo_Span[Sysset->Sys_Ozo_Sel-1]*0.132+5.7;
                       Sysctrl->BD_Interface.Fflag = 1;//阀门控制切换标志 0:出来的时候为0  1:进去的时候为1
                       Photometer_RN[0]=Photometer_RN[1]=Photometer_RN[2]="";
//                       label_Photometer->setText(Photometer_RN[0]);
//                       label_Photometer2->setText(Photometer_RN[1]);
//                       label_Photometer3->setText(Photometer_RN[2]);
                       photo_flag=0;

                   }
                   else
                   {
                       Sysset->PHOT_ENABLE = 1;
                       Sysctrl->BD_Ozonator.Vot_Set = Sysset->Ozo_Span[Sysset->Sys_Ozo_Sel-1]*0.132+5.7;
                       Sysctrl->BD_Interface.Fflag = 0;//阀门控制切换标志 0:出来的时候为0  1:进去的时候为1
                       Sysctrl->BD_Photometer.Vot_Set =   Sysset->Phot_Span *0.132+5.7 ;
                       photo_flag=1;

                   }
                   O3_RunData = Sysset->Ozo_Span[Sysset->Sys_Ozo_Sel-1];
                   Sysctrl->Sys_Ozo_Sel =Sysset->Sys_Ozo_Sel= Sysset->Sys_Ozo_Sel;
                   if(Sysset->Sys_Gas_Sel==0)   //如果当前标气选择关闭，只出臭氧
                   {
                       Sysset->Sys_Only_Ozo = O3_alone=1;  //是单独运行臭氧
                       Sysctrl->Sys_Span_Sel=Sysset->Sys_Span_sel=0;
                       Sysctrl->Total_Flow = Sysset->Ozo_ZeroAir;
                       Sysctrl->Target_Consentration=0;
                   }
                   else
                       Sysset->Sys_Only_Ozo = O3_alone=0; //不是单独运行臭氧
                   if(Sysset->Sys_Ozo_Sel>=1 && Sysset->Sys_Ozo_Sel <= 6)
                       O3_RN[0] =tr("臭氧发生器") +" "+QString::number(Sysset->Sys_Ozo_Sel);
                   else if(Sysset->Sys_Ozo_Sel ==7)
                       O3_RN[0] =tr("手动");
                   O3_RN[1]=QString("%1").arg(O3_RunData);
                   O3_RN[2]="%";
                   if(!Sysset->Sys_Run[1])
                   {
                       Sysctrl->PhotoMeter_Mode=Sysset->Sys_Run[1];
                       Sysctrl->BD_Interface.Fflag = 1;//阀门控制切换标志 0:出来的时候为0  1:进去的时候为1
                       Sysctrl->BD_Photometer.Vot_Set =0;
                       Sysctrl->BD_Ozonator.Vot_Set = Sysset->Ozo_Span[Sysset->Sys_Ozo_Sel-1]*0.132+5.7;
                       Sysset->PHOT_ENABLE = 0;
                       Photometer_RN[0]=Photometer_RN[1]=Photometer_RN[2]="";
//                       label_Photometer->setText(Photometer_RN[0]);
//                       label_Photometer2->setText(Photometer_RN[1]);
//                       label_Photometer3->setText(Photometer_RN[2]);
                       photo_flag=0;

                   }
               }
               else if(Sysset->Sys_Run[1]==3) //当光度计为控制时
               {                photo_flag=1;
                   Sysctrl->PhotoMeter_Mode=Sysset->Sys_Run[1];
                   Sysset->IS_OZO_ENABLE = 1; //其中totalflow_span代表当前总浓度
                   Sysset->PHOT_ENABLE = 1;//光度计使能
                   Sysctrl->BD_Interface.Fflag = 0;//阀门控制切换标志 0:出来的时候为0  1:进去的时候为1
                   Sysctrl->BD_Photometer.Vot_Set = Sysset->Phot_Span *0.132+5.7 ;
                   if(Sysset->Set_Ozo_Con[Sysset->Sys_Ozo_Sel-1]==0)
                       Sysctrl->BD_Ozonator.Vot_Set = 0.00;
                   else
                       Sysctrl->BD_Ozonator.Vot_Set = (0.00065 * Sysset->Ozo_ZeroAir +0.2) * Sysset->Set_Ozo_Con[Sysset->Sys_Ozo_Sel-1] + 6.64 ;      //电压与设置浓度的线性关系
                   if(Sysctrl->BD_Ozonator.Vot_Set>20.0)
                       Sysctrl->BD_Ozonator.Vot_Set = 20.0;
                   if(Sysctrl->BD_Ozonator.Vot_Set<0)
                       Sysctrl->BD_Ozonator.Vot_Set = 0;
                   O3_RunData = Sysset->Ozo_Span[Sysset->Sys_Ozo_Sel-1];
                   Sysctrl->Sys_Ozo_Sel =Sysset->Sys_Ozo_Sel= Sysset->Sys_Ozo_Sel;
                   if(Sysset->Sys_Gas_Sel==0)   //如果当前标气选择关闭，只出臭氧
                   {
                       Sysset->Sys_Only_Ozo = O3_alone=1;  //是单独运行臭氧
                       Sysctrl->Sys_Span_Sel=Sysset->Sys_Span_sel=8;
                       Sysctrl->Total_Flow = Sysset->Ozo_ZeroAir;
                       if(Sysset->Set_Ozo_Con[Sysset->Sys_Ozo_Sel-1]==0)
                       {
                           Sysctrl->BD_Ozonator.Vot_Set = 0.00;
                       }
                       else
                       {
                           Sysctrl->BD_Ozonator.Vot_Set = (0.00065 * Sysset->Ozo_ZeroAir +0.2) * Sysset->Set_Ozo_Con[Sysset->Sys_Ozo_Sel-1] + 6.64 ;      //电压与设置浓度的线性关系
                           if(Sysctrl->BD_Ozonator.Vot_Set>20.0)
                               Sysctrl->BD_Ozonator.Vot_Set = 20.0;
                           if(Sysctrl->BD_Ozonator.Vot_Set<0)
                               Sysctrl->BD_Ozonator.Vot_Set = 0;
                       }
                       Sysctrl->Target_Consentration=0;
                   }
                  else
                   Sysset->Sys_Only_Ozo = O3_alone=0; //不是单独运行臭氧
               if(Sysset->Sys_Ozo_Sel>=1 && Sysset->Sys_Ozo_Sel <= 6)
                   O3_RN[0] =tr("臭氧发生器") +" "+QString::number(Sysset->Sys_Ozo_Sel);
               else if(Sysset->Sys_Ozo_Sel ==7)
                   O3_RN[0] =tr("手动");
               O3_RN[1]=QString("%1").arg(O3_RunData);
               O3_RN[2]="%";
               BD_Ozonator_Vot_Set=Sysctrl->BD_Ozonator.Vot_Set;
           }
               qDebug()<< Sysctrl->BD_Ozonator.Vot_Set;
               if(Sysctrl->PhotoMeter_Mode && flag_daojin)
               {
                       if(Sysctrl->PhotoMeter_Mode==1||Sysctrl->PhotoMeter_Mode==2)
                       {
                           Photometer_RN[0]=tr("O3");
                           Photometer_RN[1]=(QString::number(daoji)+"秒");
                           Photometer_RN[2]="PPM";
                       }
                      else if(Sysctrl->PhotoMeter_Mode==3)
                       {
                           Photometer_RN[0]=tr("O3");
                           Photometer_RN[1]=(QString::number(daoji)+"秒");
                           Photometer_RN[2]="PPM";
                           O3_RN[0] = O3_RN[1] = O3_RN[2] = "";
//                       ui->label_GasName_2->setText(O3_RN[0]);
//                       ui->label_GasFlow_2->setText(O3_RN[1]);
//                       ui->label_PPM_2->setText(O3_RN[2]);
                       }
                       Photometer_Integral.clear();
               }
               else
                   Photometer_RN[0] = Photometer_RN[1] = Photometer_RN[2] = "";
                   Photometer_Integral.clear();
//               label_Photometer->setText(Photometer_RN[0]);
//               label_Photometer2->setText(Photometer_RN[1]);
//               label_Photometer3->setText(Photometer_RN[2]);
               //保存
               Sysctrl->Para_Save = 1;

               if(Sysctrl->PhotoMeter_Mode==3&& !flag_daojin)
               {
                           Photometer_RN[0]=tr("O3");
                           Photometer_RN[1]=QString::number(Sysctrl->Show_Ozo,'f',3);
                           Photometer_RN[2]="PPM";
                           O3_RN[0] = O3_RN[1] = O3_RN[2] = "";
//                       ui->label_GasName_2->setText(O3_RN[0]);
//                       ui->label_GasFlow_2->setText(O3_RN[1]);
//                       ui->label_PPM_2->setText(O3_RN[2]);
                       Photometer_Integral.clear();
               }

           if(Sysctrl->PhotoMeter_Mode == 0)
           {
               flag_daojin = 1;
               photo_flag=0;
               daoji=300;
               test_daoji=60;
           }

           Sysset->Sys_Run[0]=0;

           }

        });

            //数据更新
            connect(timer_tb,&QTimer::timeout,[=](){

                //读取目标零气和气体流量
                if(Sysctrl->Sys_Gas_Sel!= 0 && Sysctrl->Sys_Span_Sel != 7)
                {
                     float temp = Sysctrl->Target_Consentration/Sysset->Gas[Sysctrl->Sys_Gas_Sel-1].gasconcentration;
                     flow_g = temp*Sysctrl->Total_Flow;//ZeroFlow
                     flow_z = Sysctrl->Total_Flow-flow_g;//GasFlow
                     if(flow_z<=0) flow_z=0;
                     if(flow_g<=0) flow_g=0;
                }
                else if(Sysctrl->Sys_Gas_Sel!= 0 && Sysctrl->Sys_Span_Sel == 7)
                {
                    flow_z = Sysctrl->Zero_Flow;
                    flow_g = Sysctrl->AirFlow;
                }
                else if(Sysctrl->Sys_Gas_Sel==0)
                {
                    flow_g = flow_z = 0;
                }

            });

}

void MainWindow::WriteToFile()
{
//    if(flag_WriteToH_M ==0)
//    {
//    for(int i=2;i<TotalDataNum;i++)
//    {
//        data_aver[i] = QString::number((data_aver[i].toFloat()/(cnt_ToWrite+first_start)),'f',3);
//        data_aver[i] = QString::number(data_aver[i].toFloat());
//    }
//    cnt_ToWrite = 0;
//    finalData = "";
//    data_aver[0] =  QDateTime::currentDateTime().toString("yyyy/MM/dd");
//    data_aver[1] = QDateTime::currentDateTime().toString("HH:mm");
//    for(int i=0;i<TotalDataNum;i++)
//    {
//        finalData += data_name[i] +"_"+ data_aver[i]+ "  ";
//    }
//    finalData+="\n";
//    QString DirName2 = DirName+"/";
//    dataFile::WriteFile(DirName2+FileName+".txt",finalData);//记录一次数据
//    first_start = 1;
////    for(int i=0;i<TotalDataNum;i++)
////        data_aver[i].clear();
//    }


//    else if(flag_WriteToH_M ==1) //小时数据先屏蔽
//    {
//        for(int i=2;i<TotalDataNum;i++)
//        {
//            data_aver_H[i] = QString::number((data_aver_H[i].toFloat()/(cnt_ToWriteH+first_start_H)),'f',3);
//            data_aver_H[i] = QString::number(data_aver_H[i].toFloat());
//        }
//        cnt_ToWriteH = 0;
//        finalData = "";
//        data_aver_H[0] =  QDateTime::currentDateTime().toString("yyyy/MM/dd");
//        data_aver_H[1] = QDateTime::currentDateTime().toString("hh") + ":00";
//        QString ss = QDateTime::currentDateTime().toString("yyyy_MM_dd_hh");
//        QByteArray ba = ss.toLatin1();
//        char *str = ba.data();
//        strcpy(Sysset->TimeWrite,str);
//        for(int i=0;i<TotalDataNum;i++)
//        {
//            finalData += data_name[i] +"_"+ data_aver_H[i]+ "  ";
//        }
//        finalData+="\n";
//        QString DirName2 = DirNameL+"/";
//        DataFile_Create::WriteFile(DirName2+FileName+".txt",finalData);//记录一次数据
////        for(int i=0;i<TotalDataNum;i++)
////            data_aver_H[i].clear();
//        first_start_H=1;
//    }
}
//数据采集 每1s采集一次
QString MainWindow::data_collect()
{
    finalData ="";
    record_data[0] =  QDateTime::currentDateTime().toString("yyyy/MM/dd");
    record_data[1]  = QDateTime::currentDateTime().toString("HH/mm/ss");

    if((Sysctrl->Sys_Ozo_Sel) &&(Sysctrl->PhotoMeter_Mode!=3))//当不为光度计控制时
    {
        record_data[2] = QString::number(Sysset->Ozo_Span[Sysctrl->Sys_Ozo_Sel-1],'f',1);//臭氧发生器
    }
    else
       record_data[2] ="0";
    if(!flag_daojin)
      record_data[3] = QString::number(Sysctrl->Show_Ozo,'f',3);//O3浓度
    else
      record_data[3] ="0";
    record_data[4] = QString::number(flow_g,'f',1);//目标标气
    record_data[5] = QString::number(Sysstatus->MFC_Air_PostCal,'f',1); //实际标气
    record_data[6] = QString::number(flow_z,'f',1); //目标零气
    record_data[7] = QString::number(Sysstatus->MFC_Zero_PostCal *1000,'f',1);  //实际零气
    record_data[8] = QString::number(Sysset->Gas[Sysctrl->Sys_Gas_Sel-1].totalflow_span[Sysctrl->Sys_Span_Sel-1],'f',1);
    record_data[9] = QString::number(Sysstatus->MFC_Zero.Mass_Flow *1000 + Sysstatus->MFC_Air.Mass_Flow,'f',1);
    record_data[10] = QString::number(Sysstatus->Air_Pressure,'f',1);//压力
    record_data[11] = QString::number(Sysstatus->Ozo_TempRead,'f',1);//O3灯温度
    record_data[12] = QString::number(cnt_warn);//外部报警
    record_data[13] = QString::number(Sysstatus->Int_Temp1,'f',1);//环境温度
    record_data[14] = QString::number(Sysstatus->Phot_TempRead,'f',1);//光度计温度
    record_data[15] = QString::number(Sysstatus->Int_Temp3,'f',1);//光度计温度
    record_data[16] = QString::number(Sysset->Gas[Sysctrl->Sys_Gas_Sel-1].gasconcentration_span[Sysctrl->Sys_Span_Sel-1],'f',1);//目标标气

    if(Sysstatus->MFC_Air_PostCal<=0) Sysstatus->MFC_Air_PostCal=0;
    if(Sysstatus->MFC_Zero_PostCal<=0) Sysstatus->MFC_Zero_PostCal=0;
    float flow = Sysstatus->MFC_Air_PostCal + Sysstatus->MFC_Zero_PostCal * 1000;
    int flow_2 = flow;
    data_totalflow= QString("%1").arg(flow_2);

//    if(temp != cycle_flag)
//    {
//        if(!timer_file->isActive())
//            timer_file->start();
//        temp = cycle_flag;
//        if(cycle_flag != 0)
//            timer_file->setInterval(cycletime[cycle_flag].toFloat() * 60 *1000);//重新设置定时器更新时间
//        else //关闭定时器
//            timer_file->stop();
//    }
    aver_cnt++;
    //统计数据
    for(int aver_1=2;aver_1<TotalDataNum;aver_1++)
    {
        float aver_temp = record_data[aver_1].toFloat();
        data_aver[aver_1] += aver_temp;
    }
    //0.2s采集一次，1s做一次平均
    if(aver_cnt==5)
    {
        aver_cnt=0;
        record_data_2[0] = QString::number(data_aver[0]);
        record_data_2[1] = QString::number(data_aver[1]);

        for(int aver_2=2;aver_2<TotalDataNum;aver_2++)
        {
            record_data_2[aver_2] = QString::number(data_aver[aver_2]/5);
            data_aver[aver_2] = 0;
        }

        for(int i=0;i<TotalDataNum;i++)
        {
            finalData += data_name[i]+"_" + record_data_2[i]+ "  ";
        }
        finalData+="\n";
        file_cnt++;
    }
    if(file_cnt==60) //用于写入数据，10s往文件里写入一次
{
        QString DirName2 = DirName+"/";
        dataFile::WriteFile(DirName2+FileName+".txt",finalData);//记录一次数据
   file_cnt=0;
    }
    return finalData;
}



void MainWindow::init_data()
{
    //若第一次启动则默认3路
//if(Sysset->Gas_Num ==0)
    Sysset->Gas_Num = 3;
    Sysset->Sys_Run[0]=Sysset->Sys_Run[1]=Sysset->Sys_Gas_Sel = Sysset->Sys_Ozo_Sel = Sysset->Sys_Span_sel = 0;
    Sysctrl->Sys_Gas_Sel = Sysctrl->Sys_Ozo_Sel = Sysctrl->Sys_Span_Sel = 0;
    Sysctrl->BD_Ozonator.Vot_Set =0;
    Sysctrl->BD_Photometer.Vot_Set = 0 ;
    Sysset->IS_OZO_ENABLE = 0;
    Sysset->PHOT_ENABLE = 0;
    Sysset->Sys_Only_Ozo = 0;
    //开机更新一次默认名字
     for(name_i=0;name_i<6;name_i++)
     {
         if(qstrlen(Sysset->Gas[name_i].gasname)==0)
         {
              qstrcpy(Sysset->Gas[name_i].gasname,Gas_Selname[name_i].toLocal8Bit().data());
         }
     }
    Sysctrl->Para_Save = 1;

    //数据记录间隔
    if(Sysset->DataLog_InterVal <=1)   Sysset->DataLog_InterVal = cycle_flag;
    else cycle_flag = Sysset->DataLog_InterVal-1;
    //默认60度
    Sysctrl->BD_Ozonator.Temp_Set = 60;
    Sysctrl->BD_Photometer.Temp_Set = 50;

    //启动程序,若从未设置过便会给一个默认值
    if(Sysset->OzoTemp_H==0 && Sysset->Ozotemp_L==0)
    {
        Sysset->Ozotemp_L = 50;
        Sysset->OzoTemp_H = 85;
    }
    if(Sysset->BenchTemp_H==0 && Sysset->BenchTemp_L==0)
    {
        Sysset->BenchTemp_H = 47;
        Sysset->BenchTemp_L = 10;
    }
    if(Sysset->PhotTemp_H==0 && Sysset->PhotTemp_L==0)//光度计温度
    {
        Sysset->PhotTemp_H = 60;
        Sysset->PhotTemp_L = 45;
    }
    if(Sysset->Light_Cell_H==0 && Sysset->Light_Cell_L==0)//光池温度qt用
    {
        Sysset->Light_Cell_H = 40;
        Sysset->Light_Cell_L = 15;
    }
    //若第一次启动则默认3路
    if(Sysset->Gas_Num ==0) Sysset->Gas_Num = 3;
    //
   //开机更新一次默认名字
    for(name_i=0;name_i<6;name_i++)
    {
        if(qstrlen(Sysset->Gas[name_i].gasname)==0)
        {
             qstrcpy(Sysset->Gas[name_i].gasname,Gas_Selname[name_i].toLocal8Bit().data());
        }
    }
    Sysctrl->Para_Save =1;
    ZERO_set_data = QString("%1").arg(Sysset->ZeroMFC_Range); //零气量程
    Stand_set_data =QString("%1").arg(Sysset->GasMFC_Range);  //标气最大量程


}

void MainWindow::PID1_init(void)
{
    pid1.SetTemp=0;
    pid1.pwmduty=0;
    pid1.err=0;
    pid1.err_last=0;
    pid1.pwm=0.0;
    pid1.integral=0;
    pid1.Kp=2;
    pid1.Ki=0.15;
    pid1.Kd=0.00;
}

float MainWindow::PID1_realize(float temp)
{

    pid1.SetTemp=temp;
    pid1.err=pid1.SetTemp-Integral_aver_con;
    pid1.integral+=pid1.err;
    if(pid1.err>=-2&&pid1.err<=2)
    {
        pid1.pwm= (pid1.Kp*pid1.err)+pid1.Ki*pid1.integral+pid1.Kd*(pid1.err-pid1.err_last);
        pid1.err_last=pid1.err;

        if(pid1.pwm>18.9)
        {
            pid1.pwm=18.9;
            pid1.integral=0;
        }

            if((pid1.integral)<=-3||(pid1.integral)>=50)
            {
                pid1.integral=0;
            }
    }
    pid1.pwmduty=pid1.pwm;
    if( pid1.pwmduty<-5)
    pid1.pwmduty=0;
    return pid1.pwmduty;
}


void MainWindow::ui_Init()
{


    theBox_style[0]=("outline: 0px ;                            /* 去掉获取焦点时的虚线 */ \
                      background-color: rgb(255, 150, 55);	    /* 背景颜色 */\
                      border-radius: 6px;		                 /* 按钮边框的圆角设置 */\
                      border-style: outset;\
                      /* 按钮背景图标设置 */\
                      background-image: url(:/pic/access/气象站.png); /* 背景图片 */\
                      background-origin: content;\
                      background-position: left;	         /* 背景图片的位置 */\
                      padding-right: 0px;	    /*内边距设置*/	    \
                      padding-left: 10px;		/*  */	\
                      padding-bottom: 0px;		/*  */    \
                      padding-top: 0px;		/*  */    \
                      background-repeat: no-repeat;	         /* 设置背景图像的平铺模式 */\
                      /* 按钮文本设置 */\
                      text-align: content;			             /* 文本的位置 */\
                      font-size: 20px;\
                      color: #FFFFFF;			                 /* 文本颜色 */");
         theBox_style[1]=("\
                                        outline: 0px ;                            /* 去掉获取焦点时的虚线 */ \
                                            background-color: rgb(255, 150, 55);	    /* 背景颜色 */\
                                            border-radius: 6px;		                 /* 按钮边框的圆角设置 */\
                                            border-style: outset;\
                                            /* 按钮背景图标设置 */\
                                            background-image: url(:/pic/access/过滤.png); /* 背景图片 */\
                                            background-origin: content;\
                                            background-position: left;	         /* 背景图片的位置 */\
                                            padding-right: 0px;	    /*内边距设置*/	    \
                                            padding-left: 10px;		/*  */	\
                                            padding-bottom: 0px;	/*  */   \
                                            padding-top: 0px;		/*  */    \
                                            background-repeat: no-repeat;	         /* 设置背景图像的平铺模式 */\
                                            /* 按钮文本设置 */\
                                            text-align: content;			             /* 文本的位置 */\
                                            font-size: 22px;\
                                            qproperty-iconSize: 20px 20px;			/* 设置图标大小*/\
                                        color: rgb(125, 255, 250);			                 /* 文本颜色 */\
                                        "
                                            );



    the_StyleSheet[0] ="\
            outline: 0px ;                            /* 去掉获取焦点时的虚线 */ \
            background-color: rgb(0, 170, 255);	    /* 背景颜色 */\
            border-radius: 6px;		                 /* 按钮边框的圆角设置 */\
            border-style: outset;\
            /* 按钮背景图标设置 */\
            background-image: url(:/pic/access/气象站.png); /* 背景图片 */\
            background-origin: content;\
            background-position: top;	         /* 背景图片的位置 */\
            padding-right: 0px;	    /*内边距设置*/	    \
            padding-left: 0px;		/*  */	\
            padding-bottom: 10px;		/*  */    \
            padding-top: 10px;		/*  */    \
            background-repeat: no-repeat;	         /* 设置背景图像的平铺模式 */\
            /* 按钮文本设置 */\
            text-align: bottom;			             /* 文本的位置 */\
            font-size: 20px;\
            color: #FFFFFF;			                 /* 文本颜色 */\
";

the_StyleSheet[1]="   outline: 0px ;                            /* 去掉获取焦点时的虚线 */ \
        background-color: rgb(255,125,25);	    /* 背景颜色 */\
        border-radius: 6px;		                 /* 按钮边框的圆角设置 */\
        border-style: outset;\
        /* 按钮背景图标设置 */\
        background-image: url(:/pic/access/过滤.png); /* 背景图片 */\
        background-origin: content;\
        background-position: top;	         /* 背景图片的位置 */\
        padding-right: 0px;	    /*内边距设置*/	    \
        padding-left: 0px;		/*  */	\
        padding-bottom: 10px;	/*  */   \
        padding-top: 10px;		/*  */    \
        background-repeat: no-repeat;	         /* 设置背景图像的平铺模式 */\
        /* 按钮文本设置 */\
        text-align: bottom;			             /* 文本的位置 */\
        font-size: 22px;\
        qproperty-iconSize: 20px 20px;			/* 设置图标大小*/\
        color: rgb(255, 255, 250);			                 /* 文本颜色 */\ ";

the_StyleSheet[2]="     background-color: rgb(0, 170, 255);	    /* 背景颜色 */ ";
the_StyleSheet[3]="  border-radius: 6px;		                 /* 按钮边框的圆角设置 */ ";
the_StyleSheet[4]="   border-style: outset; ";
the_StyleSheet[5]="   background-image: url(:/pic/Mainwindow/运行.png); /* 背景图片 */";
the_StyleSheet[6]="   background-origin: content;";
the_StyleSheet[7]="   background-position: top;	 /* 背景图片的位置 */";
the_StyleSheet[8]="   padding-right: 0px;	    /*内边距设置*/    padding-left: 0px;		/*  */	   padding-bottom: 10px;		/*  */        padding-top: 10px;	";
the_StyleSheet[9]="   background-repeat: no-repeat;	         /* 设置背景图像的平铺模式 */";
the_StyleSheet[10]="     /* 按钮文本设置 */\
        text-align: bottom;			             /* 文本的位置 */\
        font-size: 20px;\
        color: #FFFFFF;			                 /* 文本颜色 */";
the_StyleSheet[11]="}";
the_StyleSheet[12]="background-color: rgb(255,125,25);	";
the_StyleSheet[13]="  /* 按钮文本设置 */\
        text-align: bottom;			             /* 文本的位置 */\
        font-size: 22px;\
        color: rgb(125, 255, 250);			                 /* 文本颜色 */";
the_StyleSheet[15]="   background-image: url(:/pic/Mainwindow/运行2.png); /* 背景图片 */";

        for(int i=0;i<8;i++)//创建主屏幕显示的按键
    {
         focusBtn[i] = new QPushButton(this);
//        newbutton->setGeometry(30+(i*150),260,120,90 );//设定每隔放置一个按键
        focusBtn[i]->setFixedSize(120,90);
        focusBtn[i]->geometry();
//         "QPushButton:focus{"+the_StyleSheet[1]+"color: rgb(255,125,25);	  /* 文本颜色 */"+"background-color: rgb(220, 50, 105);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/返回2.png); /* 背景图片 */"+"}");

//        newbutton->setIconSize(QSize(1,2));
btnlist_ui.append(focusBtn[i]);

    }
        focusBtn[0]->setStyleSheet(  "QPushButton{"+the_StyleSheet[0]+"background-color: rgb(0, 250, 155);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/Mainwindow/运行.png); /* 背景图片 */"+"}"
        "QPushButton:focus{"+the_StyleSheet[1]+"background-color: rgb(0, 250, 155);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/Mainwindow/运行2.png); /* 背景图片 */"+"}");
        focusBtn[1]->setStyleSheet(  "QPushButton{"+the_StyleSheet[0]+"background-color: rgb(250, 200, 10);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/Mainwindow/气体设置.png); /* 背景图片 */"+"}"
         "QPushButton:focus{"+"background-color: rgb(250, 200, 10);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/Mainwindow/气体设置2.png); /* 背景图片 */"+"}");
        focusBtn[2]->setStyleSheet(  "QPushButton{"+the_StyleSheet[0]+"background-color: rgb(250, 100, 100);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/Mainwindow/气流模式.png); /* 背景图片 */"+"}"
         "QPushButton:focus{"+"background-color: rgb(250, 100, 100);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/Mainwindow/气流模式2.png); /* 背景图片 */"+"}");
        focusBtn[3]->setStyleSheet(  "QPushButton{"+the_StyleSheet[0]+"background-color: rgb(250, 10, 10);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/Mainwindow/臭氧发生器.png); /* 背景图片 */"+"}"
         "QPushButton:focus{"+"background-color: rgb(250, 10,10);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/Mainwindow/臭氧发生器2.png); /* 背景图片 */"+"}");
          focusBtn[4]->setStyleSheet(  "QPushButton{"+the_StyleSheet[0]+"background-color: rgb(10, 150, 155);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/Mainwindow/仪器设置.png); /* 背景图片 */"+"}"
         "QPushButton:focus{"+"background-color: rgb(10, 150, 155);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/Mainwindow/仪器设置2.png); /* 背景图片 */"+"}");
        focusBtn[5]->setStyleSheet(  "QPushButton{"+the_StyleSheet[0]+"background-color: rgb(50, 200, 200);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/Mainwindow/诊断.png); /* 背景图片 */"+"}"
         "QPushButton:focus{"+"background-color: rgb(50, 200, 200);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/Mainwindow/诊断2.png); /* 背景图片 */"+"}");
        focusBtn[6]->setStyleSheet(  "QPushButton{"+the_StyleSheet[0]+"background-color: rgb(100, 150, 250);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/Mainwindow/报警.png); /* 背景图片 */"+"}"
         "QPushButton:focus{"+"background-color: rgb(100, 150, 250);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/Mainwindow/报警2.png); /* 背景图片 */"+"}");
        focusBtn[7]->setStyleSheet(  "QPushButton{"+the_StyleSheet[0]+"background-color: rgb(150, 50, 250);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/Mainwindow/维护.png); /* 背景图片 */"+"}"
         "QPushButton:focus{"+"background-color: rgb(150, 50, 250);	    /* 背景颜色 */ ;"+ "background-image: url(:/pic/Mainwindow/维护2.png); /* 背景图片 */"+"}");

btnlist_ui.at(0)->setText(tr("运行"));
btnlist_ui.at(1)->setText(tr("气体设置"));
btnlist_ui.at(2)->setText(tr("气流设置"));
btnlist_ui.at(3)->setText(tr("单片机设置"));
btnlist_ui.at(4)->setText(tr("仪器设置"));
btnlist_ui.at(5)->setText(tr("诊断"));
btnlist_ui.at(6)->setText(tr("警报"));
btnlist_ui.at(7)->setText(tr("维护"));

QGridLayout *mainLayout = new QGridLayout();
QGridLayout *mainLayout2 = new QGridLayout();
mainLayout->addWidget(btnlist_ui.at(0), 1, 0);
mainLayout->addWidget(btnlist_ui.at(1), 1, 1);
mainLayout->addWidget(btnlist_ui.at(2), 1, 2);
mainLayout->addWidget(btnlist_ui.at(3), 1, 3);
//mainLayout->setVerticalSpacing(50);
//mainLayout->setHorizontalSpacing(10);
mainLayout->setContentsMargins(0,120,0,0);//(int left, int top, int right, int bottom)
//mainLayout->setColumnStretch(1,22);
mainLayout->setSizeConstraint(QLayout::SetMinimumSize);//布局显示效果
  setLayout(mainLayout);
  mainLayout2->addWidget(btnlist_ui.at(4), 1, 0);
  mainLayout2->addWidget(btnlist_ui.at(5), 1, 1);
  mainLayout2->addWidget(btnlist_ui.at(6), 1, 2);
  mainLayout2->addWidget(btnlist_ui.at(7), 1, 3);
//  mainLayout2->setVerticalSpacing(50);
//  mainLayout2->setHorizontalSpacing(20);
  mainLayout2->setContentsMargins(0,50,0,0);//(int left, int top, int right, int bottom)
  mainLayout2->setSizeConstraint(QLayout::SetMinimumSize);
    setLayout(mainLayout2);
  QWidget* widget = new QWidget(this);
  QWidget* widget2 = new QWidget(this);
  widget->setGeometry(0,0,640,200);
  widget2->setGeometry(0,200,640,200);
  widget->setLayout(mainLayout);
  widget2->setLayout(mainLayout2);

the_StyleSheet[20]="          outline: 0px ;                            /* 去掉获取焦点时的虚线 */ \
      background-color: rgb(0, 22, 225);	    /* 背景颜色 */ \
      border-radius: 0px;		                 /* 按钮边框的圆角设置 */\
      border-style: outset;\
         /* 按钮文本设置 */\
         qproperty-alignment: 'AlignCenter| AlignCenter';			             /* 文本的位置 */\
         font-size: 20px;\
           color: rgb(255, 255, 255);		                 /* 文本颜色 */";
         the_StyleSheet[21]="background-color: rgb(200, 1, 255);	    /* 背景颜色 */";
         the_StyleSheet[22]="  image: url(:/pic/报警.png);";//图标

  for(int i=0;i<6;i++)//创建主屏幕显示的按键
  {
       theLabel[i] = new QLabel(this);
  }
         theLabel[0]->setStyleSheet("QLabel{"
                               + the_StyleSheet[20] +   "}"    );
         theLabel[1]->setStyleSheet("QLabel{"
                               + the_StyleSheet[20] + the_StyleSheet[21]+  "}"    );
         theLabel[2]->setStyleSheet("QLabel{"
                               + the_StyleSheet[20] + the_StyleSheet[22]+  "}"    );
         the_StyleSheet[22]="  image: url(:/pic/Mainwindow/维护.png);";//图标
         theLabel[3]->setStyleSheet("QLabel{"
                               + the_StyleSheet[20] + the_StyleSheet[22]+  "}"    );
         theLabel[4]->setStyleSheet("QLabel{  image: url(:/pic/logo.png);}"    );
         theLabel[5]->setStyleSheet("QLabel{  image: url(:/pic/Instrument/密码.png);}"    );
  theLabel[0]->setGeometry(0,430,640,50);//设定每隔放置一个按键
  theLabel[1]->setGeometry(500,430,120,50);//设定每隔放置一个按键
  theLabel[2]->setGeometry(400,430,50,50);//设定每隔放置一个按键
  theLabel[3]->setGeometry(350,430,50,50);//设定每隔放置一个按键
  theLabel[5]->setGeometry(300,430,50,50);//设定每隔放置一个按键
  theLabel[4]->setGeometry(0,0,150,60);//设定每隔放置一个按键

  QString timeNowHM = QDateTime::currentDateTime().toString("hh:mm:ss");
  QString timeNowYD = QDateTime::currentDateTime().toString("yyyy.MM.dd");
  QString TimeNow ="  "+timeNowHM+"\n"+timeNowYD;
  theLabel[1]->setText(TimeNow);


  if(Sysset->Back_light_ratio==0)
  {
      Sysset->Back_light_ratio = 80;
      int num_light = 80*7/100;
      QString s = "echo "+QString::number(num_light)+" > /sys/devices/platform/backlight/backlight/backlight/brightness";
      QByteArray byte = s.toLatin1();//必须加
      system(byte.data());
      Sysctrl->Para_Save = 1;
  }
  else
  {
      int num_light = Sysset->Back_light_ratio*7/100;
      QString s = "echo "+QString::number(num_light)+" > /sys/devices/platform/backlight/backlight/backlight/brightness";
      QByteArray byte = s.toLatin1();//必须加
      system(byte.data());
  }
  //设置间隔
  Sysset->ReadInterval = 500;//间隔默认500ms
  Sysctrl->Para_Save=1;

  qstrcpy(Sysset->password,"000000");

//事件过滤器
foreach (QPushButton *btn, btnlist_ui) {
    btn->installEventFilter(this);
}
  //校准零
  connect(btnlist_ui.at(0),&QPushButton::clicked,[=](){

            MainMenu  *menux = new MainMenu(this);
            menux->show();

  });

  //气体设置
  connect(btnlist_ui.at(1),&QPushButton::clicked,[=](){

      Airflow_Menu  *menux = new Airflow_Menu(this);
      menux->show();

  });

  //气流设置
  connect(btnlist_ui.at(2),&QPushButton::clicked,[=](){

      gasSet_Menu  *menux = new gasSet_Menu(this);
      menux->show();
                  connect(menux,&gasSet_Menu::destroyed,[=](){
btnlist_ui.at(2)->setFocus();
                  });
  });

  //单片机设置
  connect(btnlist_ui.at(3),&QPushButton::clicked,[=](){
if(Photometer_Flag||O3_Show_Flag)
{
    Set_O3_Photo*board = new Set_O3_Photo(this);
    board->show();
}

  });

  //仪器设置
  connect(btnlist_ui.at(4),&QPushButton::clicked,[=](){
      instrumrnt_Menu *board = new instrumrnt_Menu(this);
      board->show();

  });

  //诊断
  connect(btnlist_ui.at(5),&QPushButton::clicked,[=](){
      Diagnosis_Menu *board = new Diagnosis_Menu(this);
      board->show();

  });

  //警报
  connect(btnlist_ui.at(6),&QPushButton::clicked,[=](){
      Warning_Menu *board = new Warning_Menu(this);
      board->show();

  });

  //诊断
  connect(btnlist_ui.at(7),&QPushButton::clicked,[=](){

      if(Photometer_Flag)
      {
          Maintain_Menu *board = new Maintain_Menu(this);
          board->show();
      }
      else{
          Maintain_Menu2 *board = new Maintain_Menu2(this);
          board->show();
      }


  });
}


  void MainWindow::test_srf(QString text)
  {
      btnlist_ui.at(4)->setText(text);

  }


bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{

//            key_Event::key_Event1(pos,watched, event, btnlist, btnlist_ui);
        for(int i=0;i<btnlist_ui.length();i++)
            if(btnlist_ui.at(i) == watched)
        {
            if(event->type() == QEvent::KeyPress)
            {
               QKeyEvent *ev = (QKeyEvent *)event;
               QPushButton *button = (QPushButton *)watched;
               switch (ev->key())
               {
               case OK:
                 {
                   emit  button->clicked();
                   break;
                 }
               case UP://上
               {
                   if(focusWidget() != btnlist_ui.first())
                   {
                       focusPreviousChild();
                       focusPreviousChild();
                       focusPreviousChild();
                       focusPreviousChild();
                   }
                   break;
               }
               case DOWN://下
               {
                   if(focusWidget() != btnlist_ui.back())
                   {
                       focusNextChild();
                       focusNextChild();
                       focusNextChild();
                       focusNextChild();
                   }
                   break;
               }
               case LEFT://左
               {
                 if(focusWidget() != btnlist_ui.first())
                      focusPreviousChild();
                 break;
               }
               case RIGHT://右
               {
                 if(focusWidget() != btnlist_ui.back())
                      focusNextChild();
              break;
               }
               case INIT: //打开初始化界面
               {
                   init_Show *show = new init_Show(this);
                   show->show();
                   this->hide();
                   break;
               }

               default:
                   break;
               }
            }
            else if (event->type()==QEvent::FocusIn)     //然后再判断控件的具体事件 (这里指获得焦点事件)
                      {
                          QPushButton *focus_button = (QPushButton *)watched;
                                  focus_button->setFixedSize(160,120);
//                                  focus_button->setStyleSheet(focusBtn[2]->styleSheet());
//                                  focus_button->setIconSize(QSize(1,2));
                      }
            else if (event->type()==QEvent::FocusOut)    // 这里指 控件的失去焦点事件
                     {
                QPushButton *focus_button = (QPushButton *)watched;
                        focus_button->setFixedSize(120,90);
                     }
            }
}

void MainWindow::data_recordInit()
{
    for(int i=0;i<TotalDataNum;i++)
    {
        data_name[i]=data_name2[i];
    }

}

void MainWindow::data_Record()
{
    //首先创建一个专门存放数据的文件夹datalog
    //实例QDir
    testdata=QDateTime::currentDateTime()/*.addDays(datei++)*/;
    FileName = testdata.toString("yyyy_MM_dd");//第一个文件的名字
    DirName="/File_reMake/Datalog/"+QDateTime::currentDateTime().toString("yyyy_MM"); //第一个文件夹名字;
    DirNameL="/File_reMake/DatalogL/"+QDateTime::currentDateTime().toString("yyyy_MM"); //第一个文件夹名字;
    QString DirName2 = DirName+"/"; //写入文本到文件夹
    dataFile::CreateDir(DirName);  //立即创建第一个文件夹，但第一个文件要之后在建立
    dataFile::CreateDir(DirNameL);  //立即创建第一个文件夹，但第一个文件要之后在建立
//    for(int i=0;i<TotalDataNum;i++)
//    {
//       qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));//测试数据，生成随机数，

//        data_aver[i] = QString::number(qrand()%10);
//    }
//    for(int i=0;i<TotalDataNum;i++)
//    {
//        finalData += data_name2[i] +"_"+ data_aver[i]+ "  ";
//    }
//    finalData+="\n";
//    dataFile::WriteFile(DirName2+FileName+".txt",finalData);//记录一次数据
}


bool MainWindow::DeleteFileOrFolder(const QString &strPath)
{
    if (strPath.isEmpty() || !QDir().exists(strPath))//是否传入了空的路径||路径是否存在
        return false;

    QFileInfo FileInfo(strPath);

    if (FileInfo.isFile())//如果是文件
        QFile::remove(strPath);
    else if (FileInfo.isDir())//如果是文件夹
    {
        QDir qDir(strPath);
        qDir.removeRecursively();
    }
    return true;
}

QStringList MainWindow::GetDirNameList(const QString &strDirpath)
{
    QDir dir(strDirpath);
    dir.setSorting(QDir::Time| QDir::Reversed); //按时间先后排序，从最早到最新
    QFileInfoList Info_list = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
    QListIterator<QFileInfo> Iterator(Info_list);
    QStringList strDirNameList;
    QFileInfo Info;
    while (Iterator.hasNext())
    {
        Info = Iterator.next();
        if (Info.isDir())
        {
            strDirNameList << QDir(Info.absoluteFilePath()).dirName();
//            qDebug()<<QDir(Info.absoluteFilePath()).dirName();
        }
    }
    return strDirNameList;
}

void MainWindow::delexpiredfile(const QString &strDirpath)
{
    QStringList foldername=GetDirNameList(strDirpath);//获取文件夹内所有文件并根据修改日期进行排序
    {

        QString str;
        //删除文件夹中最早修改的文件
//                for (int i = 0; i < foldername.size()-5; i++)
        {
            str= strDirpath + "/" + foldername.at(0);
            qDebug()<<foldername.at(0)<<endl;
           DeleteFileOrFolder(str);
        }

    }

    return;
}
